package com.googlecode.esblabs.order.esbadapter.test;

import java.io.InputStream;
import java.io.StringReader;
import java.io.StringWriter;

import javax.xml.bind.JAXBElement;

import org.mule.api.MuleEventContext;
import org.mule.config.ReaderInputStream;
import org.mule.tck.functional.FunctionalTestComponent;

import com.googlecode.esblabs.cmf.AcknowledgeSalesOrderDataAreaType;
import com.googlecode.esblabs.cmf.AcknowledgeSalesOrderType;
import com.googlecode.esblabs.cmf.ProcessSalesOrderType;
import com.googlecode.esblabs.cmf.SalesOrderType;
import com.googlecode.esblabs.util.io.WriterOutputStream;
import com.googlecode.esblabs.util.mule.transformer.jaxb.XmlBinding;

public class ProxyComponent extends FunctionalTestComponent{

	@Override
	protected Object process(Object data, MuleEventContext context) throws Exception {

		// Convert the XML message to a ProcessSalesOrderType
        InputStream is = new ReaderInputStream(new StringReader((String)data));
        ProcessSalesOrderType payload = ((JAXBElement<ProcessSalesOrderType>)XmlBinding.unmarshal(ProcessSalesOrderType.class, is)).getValue();

        // Do some basic data validation
		if (payload.getDataArea().getSalesOrder().size() == 0) {
			throw new RuntimeException("*** Missing Sales Order ***");
		}
		
		// Take out the sales order
		SalesOrderType salesOrder = payload.getDataArea().getSalesOrder().get(0);

		
		// Create a AcknowledgeSalesOrderType - reply based on the sales order
		AcknowledgeSalesOrderType result = new AcknowledgeSalesOrderType();
		AcknowledgeSalesOrderDataAreaType da = new AcknowledgeSalesOrderDataAreaType();
		result.setDataArea(da);
		da.getSalesOrder().add(salesOrder);
				
		// Convert back to a XML message
        StringWriter sw = new StringWriter();
        XmlBinding.marshal(result, new WriterOutputStream(sw));

        // Send the message back...
        return super.process(sw.getBuffer().toString(), context);
	}

}
